package com.hzit.security.service;

import com.hzit.security.entity.LoginUser;
import com.hzit.security.entity.User;
import com.hzit.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：UserDetailsService实现类
 */
@Service
public class MyUserDetailService implements UserDetailsService {
	@Autowired
	private UserMapper userMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//1. 根据用户名查询用户
		User user = userMapper.selectByPrimaryKey(username);
		//2. 判断用户是否存在
		if(user == null){
			throw new UsernameNotFoundException("用户名或密码输入有误！");
		}
		//3. 得到用户的权限串列表
		List<String> permissions = userMapper.findPermissionsByUsername(username);
		//4. 使用lamba表达式及stream流式编程完成转换
		// SimpleGrantedAuthority::new相当于：new SimpleGrantedAuthority(sss)
		// List<SimpleGrantedAuthority> collect = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
		//5. 返回UserDetails对象
		return new LoginUser(user,permissions);
	}
}
